﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuXuatHang : Form
    {
        public event FormClosePhieuNhapKhoEventHandler fromClosePhieuXuatHang = null;
        private PhieuXuatHangManagement phieuxuathangMgt = new PhieuXuatHangManagement();
        private CTPhieuXuatHangManagement ctphieuxuathangMgt = new CTPhieuXuatHangManagement();        
        private ChiNhanhKhachHangManagement chinhanhkhachangMgt = new ChiNhanhKhachHangManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private KhachHangManagement khachhangMgt = new KhachHangManagement();
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private KhayDungManagement khaydungMgt = new KhayDungManagement();        
        private HangHoaManagement hanghoaMgt = new HangHoaManagement();        
        private KhoManagement khoMgt = new KhoManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private DonViTinhMgt donvitinhMgt = new DonViTinhMgt();
        private BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private int idLoaiPhieu = 8;
        private bool isEdited = false;
        public bool isPrinting = false;
        private NhanVien nhanvien;
        private PhieuXuatHang mphieuxuathang;
        private List<CTPhieuXuatHang> lstmCTphieuxuathang;
        private List<CTPhieuXuatHang> lstDeleteCTPhieuXuatHang = new List<CTPhieuXuatHang>();

        public FrmChoCuocGoi parentFrmChoCuocGoi;
        public FrmGoiMoiHang parentFrmGoiMoiHang;
        public bool IsEdited
        {
            set { this.isEdited = value; }
            get { return this.isEdited; }
        }

        public PhieuXuatHang PhieuXuatHang
        {
            set { this.mphieuxuathang = value; }
            get { return this.mphieuxuathang; }
        }

        public List<CTPhieuXuatHang> ListCTphieuxuathang
        {
            set { this.lstmCTphieuxuathang = value; }
            get { return this.lstmCTphieuxuathang; }
        }

        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        public FrmPhieuXuatHang()
        {
            InitializeComponent();
        }

        public void LoadAll()
        {
            cboTenHang.DataSource = null;
            cboTenHang.DataSource = GetAllHangHoa();
            cboTenHang.DisplayMember = "Ten";
            cboTenHang.ValueMember = "MaSo";

            cboKhachHang.DataSource = null;
            cboKhachHang.DataSource = GetAllKhachHang();
            cboKhachHang.DisplayMember = "Ten";
            cboKhachHang.ValueMember = "Id";

            cboChiNhanhCongTy.DataSource = null;
            cboChiNhanhCongTy.DataSource = GetAllChiNhanhCongTy();
            cboChiNhanhCongTy.DisplayMember = "TenChiNhanh";
            cboChiNhanhCongTy.ValueMember = "Id";

            cboDonvitinh.DataSource = null;
            cboDonvitinh.DataSource = GetAllDonViTinh();
            cboDonvitinh.DisplayMember = "TenDVT";
            cboDonvitinh.ValueMember = "TenDVT";

            cboPrefix.DataSource = GetAllBangMaPhieu(idLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";

            if (!isEdited)
            {
                btnThoat.Enabled = true;

                txtNguoiLap.Text = this.nhanvien.HoTen;
                txtMaSoThue.Text = "";
                txtSoHDD.Text = "";
                txtTongTienHang.Text = "0";
                txtTienBaoBi.Text = "0";
                txtTienVAT.Text = "0";
                txtTienChietKhau.Text = "0";
                txtTongCong.Text = "0";
                cboKhachHang.SelectedIndex = 2;

                if (parentFrmChoCuocGoi != null)
                {
                    if (parentFrmChoCuocGoi.khachhang.Id != 0)
                        cboKhachHang.SelectedItem = parentFrmChoCuocGoi.khachhang;
                    else
                        cboKhachHang.SelectedIndex = 0;
                }
                else if (parentFrmGoiMoiHang != null)
                {
                    if (parentFrmGoiMoiHang.khachhang.Id != 0)
                        cboKhachHang.SelectedItem = parentFrmGoiMoiHang.khachhang;
                    else
                        cboKhachHang.SelectedIndex = 0;
                }

                dgvChiTiet.Columns["colDonGia"].ReadOnly = false;
                dgvChiTiet.Columns["colThanhTien"].ReadOnly = false;

                dgvChiTiet.Rows.Clear();
            }
            else
            {
                lstmCTphieuxuathang = (from ctpxh in GetAllCTPhieuXuatHang()
                                        where ctpxh.IdPhieuXuatHang == this.mphieuxuathang.Id && ctpxh.IsDelete == 0
                                        select ctpxh).ToList();
                
                long tienbaobi = 0;
                cboKhachHang.Text = this.mphieuxuathang.KhachHang;
                cboChiNhanhKhachHang.Text = this.mphieuxuathang.ChiNhanhKhachHang;

                dtOld = this.mphieuxuathang.NgayThang;
                dtpNgayThang.Value = this.mphieuxuathang.NgayThang;

                prefixOld = mphieuxuathang.Prefix;
                cboPrefix.Text = mphieuxuathang.Prefix;
                txtMaSo.Text = mphieuxuathang.OrderNumber;
                
                txtNguoiLap.Text = this.mphieuxuathang.NguoiLap;
                txtMaSoThue.Text = this.mphieuxuathang.MaSoThue;                
                cboHTTT.Text = this.mphieuxuathang.HinhThucThanhToan;
                txtDiaChiGiaoHang.Text = this.mphieuxuathang.DiaChi;
                cboChiNhanhCongTy.SelectedValue = this.mphieuxuathang.IdChiNhanhCongTy;
                txtSoHDD.Text = string.IsNullOrEmpty(this.mphieuxuathang.SoHoaDonDo)? "" : this.mphieuxuathang.SoHoaDonDo.Substring(7);
                txtTongTienHang.Text = this.mphieuxuathang.TongTienHang.ToString();
                txtChietKhau.Text = this.mphieuxuathang.ChietKhau.ToString();
                txtTienChietKhau.Text = this.mphieuxuathang.TienChietKhau.ToString();
                txtVAT.Text = this.mphieuxuathang.VAT.ToString();
                txtTienVAT.Text = this.mphieuxuathang.TienVAT.ToString();
                txtTongCong.Text = this.mphieuxuathang.TongCong.ToString();
                lblId.Text = this.mphieuxuathang.Id.ToString();

                dgvChiTiet.Columns["colDonGia"].ReadOnly = true;
                dgvChiTiet.Columns["colThanhTien"].ReadOnly = false;

                for (int i = 0; i < this.lstmCTphieuxuathang.Count; i++)
                {
                    DataGridViewRow row = new DataGridViewRow();

                    DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
                    List<HangHoa> lstHangHoa = GetAllHangHoa();
                    cboCell.DataSource = lstHangHoa;
                    cboCell.DisplayMember = "Ten";
                    cboCell.ValueMember = "MaSo";
                    cboCell.Value = this.lstmCTphieuxuathang[i].MaHang;
                    if (this.lstmCTphieuxuathang[i].MaHang.Substring(0, 1).ToLower() == "8" || this.lstmCTphieuxuathang[i].MaHang.Substring(0, 1).ToLower() == "9")
                        tienbaobi += this.lstmCTphieuxuathang[i].ThanhTien;
                    row.Cells.Add(cboCell);

                    DataGridViewCell cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].MaHang;
                    row.Cells.Add(cell);

                    cboCell = new DataGridViewComboBoxCell();
                    cboCell.DataSource = GetAllDonViTinh();
                    cboCell.DisplayMember = "TenDVT";
                    cboCell.ValueMember = "TenDVT";
                    cboCell.Value = this.lstmCTphieuxuathang[i].DonViTinh;
                    row.Cells.Add(cboCell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].SoLuong;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].DonGia;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].ThanhTien;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].SoKG;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].DonViTinhQuyDoi;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].SoLuongQuyDoi;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = this.lstmCTphieuxuathang[i].Id;
                    row.Cells.Add(cell);

                    dgvChiTiet.Rows.Add(row);
                }

                txtTienBaoBi.Text = tienbaobi.ToString();

                if (isPrinting)
                {
                    btnInPhieu.Enabled = true;
                    btnInHoaDon.Enabled = true;
                    btnDinhKhoan.Enabled = true;
                    btnLuu.Enabled = true;
                }
            }
        }

        private void FrmPhieuXuatHang_Load(object sender, EventArgs e)
        {
            LoadAll();
            btnThoat.Enabled = true;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.Rows.Count <= 1 || cboHTTT.Text == "")
            {
                MessageBox.Show("Bạn chưa nhập đầy đủ dữ liệu. !!!");
                return;
            }
            
            if (dgvChiTiet.Rows.Count > 1)
            {
                ResultObj resultObj = new ResultObj();

                for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                {
                    if (dgvChiTiet.Rows[i].Cells[0].Value == null || dgvChiTiet.Rows[i].Cells[2].Value == null || dgvChiTiet.Rows[i].Cells[3].Value == null || dgvChiTiet.Rows[i].Cells[4].Value == null)
                    {
                        MessageBox.Show("Vui lòng nhập đầy đủ thông tin trong danh sách !","Thông báo");
                        return;
                    }
                }
                
                PhieuXuatHang phieuxuathang = new PhieuXuatHang();
                phieuxuathang.Prefix = cboPrefix.Text;
                phieuxuathang.OrderNumber = txtMaSo.Text;
                phieuxuathang.MaSo = cboPrefix.Text + "/" + dtpNgayThang.Value.ToString("MM") + dtpNgayThang.Value.ToString("yy") + "/" + txtMaSo.Text;
                phieuxuathang.History = "";

                phieuxuathang.NgayThang = dtpNgayThang.Value;
                phieuxuathang.NguoiLap = txtNguoiLap.Text;
                phieuxuathang.KhachHang = ((KhachHang)cboKhachHang.SelectedItem).Ten;
                phieuxuathang.MaSoThue = txtMaSoThue.Text;
                phieuxuathang.ChiNhanhKhachHang = (cboChiNhanhKhachHang.Items.Count > 0 ? ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Ten : "");
                phieuxuathang.HinhThucThanhToan = cboHTTT.Text;
                phieuxuathang.DiaChi = txtDiaChiGiaoHang.Text;
                phieuxuathang.IdChiNhanhCongTy = Convert.ToInt32(cboChiNhanhCongTy.SelectedValue.ToString());
                phieuxuathang.SoHoaDonDo = txtSoHDD.Text != "" ? lblSoHDD.Text + " " + txtSoHDD.Text : "";
                phieuxuathang.TongTienHang = Convert.ToInt64(txtTongTienHang.Text);
                phieuxuathang.ChietKhau = Convert.ToInt64(txtChietKhau.Text);
                phieuxuathang.TienChietKhau = Convert.ToInt64(txtTienChietKhau.Text);
                phieuxuathang.VAT = Convert.ToInt64(txtVAT.Text);
                phieuxuathang.TienVAT = Convert.ToInt64(txtTienVAT.Text);
                phieuxuathang.TongCong = Convert.ToInt64(txtTongCong.Text);
                DateTime dt = new DateTime(1753, 1, 1);
                phieuxuathang.NgayKiemTraHang = dt;
                phieuxuathang.NgayChungTu = dt;
                phieuxuathang.IsDelete = 0;

                //luu nhung chua duyet
                if (!isEdited)
                {
                    resultObj = phieuxuathangMgt.SaveNewPhieuXuatHang(phieuxuathang);
                    lblId.Text = resultObj.ReturnCode.ToString();
                    this.mphieuxuathang = phieuxuathang;
                    this.mphieuxuathang.Id = resultObj.ReturnCode;
                    for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        CTPhieuXuatHang ctphieuxuathang = new CTPhieuXuatHang();

                        ctphieuxuathang.IdPhieuXuatHang = Convert.ToInt32(lblId.Text);
                        ctphieuxuathang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctphieuxuathang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctphieuxuathang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctphieuxuathang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                        ctphieuxuathang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                        ctphieuxuathang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                        ctphieuxuathang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                        ctphieuxuathang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                        ctphieuxuathang.SoKG = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].FormattedValue.ToString());
                        ctphieuxuathang.IsDelete = 0;

                        resultObj = ctphieuxuathangMgt.SaveNewCTPhieuXuatHang(ctphieuxuathang);
                        dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode.ToString();
                    }
                }
                //cap nhat cho dinh khoan va in phieu
                else
                {
                    phieuxuathang.Id = this.mphieuxuathang.Id;
                    phieuxuathang.MaSo = this.mphieuxuathang.MaSo;
                    phieuxuathang.NgayKiemTraHang = this.mphieuxuathang.NgayKiemTraHang;
                    phieuxuathang.NguoiKiemTraHang = this.mphieuxuathang.NguoiKiemTraHang;
                    phieuxuathang.KeToanTruong = this.mphieuxuathang.KeToanTruong;
                    phieuxuathang.NgayChungTu = this.mphieuxuathang.NgayChungTu;
                    phieuxuathang.IsDelete = 0;
                    this.mphieuxuathang = phieuxuathang;

                    resultObj = phieuxuathangMgt.UpdatePhieuXuatHang(phieuxuathang);

                    if(this.lstmCTphieuxuathang != null)
                        lstmCTphieuxuathang.Clear();

                    lstmCTphieuxuathang = (from ctpxh in GetAllCTPhieuXuatHang()
                                               where ctpxh.IdPhieuXuatHang == this.mphieuxuathang.Id
                                               select ctpxh).ToList();

                    //Tim ra so dong update that su sau khi da xoa hoac chua xoa
                    int countUpdate = this.lstmCTphieuxuathang.Count - this.lstDeleteCTPhieuXuatHang.Count;
                    int countInsert = 0;

                    //TIm so dong moi' ma` nguoi` dung` vua` them vao`
                    if ((dgvChiTiet.Rows.Count - countUpdate) > 1)
                        countInsert = dgvChiTiet.Rows.Count - countUpdate;

                    if(countUpdate > 0)
                    {
                        for (int i = 0; i < countUpdate; i++)
                        {
                            CTPhieuXuatHang ctphieuxuathang = new CTPhieuXuatHang();

                            ctphieuxuathang.IdPhieuXuatHang = this.mphieuxuathang.Id;
                            ctphieuxuathang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                            ctphieuxuathang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                            ctphieuxuathang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                            ctphieuxuathang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                            ctphieuxuathang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                            ctphieuxuathang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                            ctphieuxuathang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                            ctphieuxuathang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                            ctphieuxuathang.SoKG = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value.ToString());
                            ctphieuxuathang.IsDelete = 0;
                            ctphieuxuathang.Id = Convert.ToInt32(dgvChiTiet.Rows[i].Cells[9].Value.ToString());

                            resultObj = ctphieuxuathangMgt.UpdateCTPhieuXuatHang(ctphieuxuathang);                            
                        }
                    }

                    if (countInsert > 1)
                    {
                        for (int i = countUpdate; i < dgvChiTiet.Rows.Count - 1; i++)
                        {
                            CTPhieuXuatHang ctphieuxuathang = new CTPhieuXuatHang();

                            ctphieuxuathang.IdPhieuXuatHang = this.mphieuxuathang.Id;
                            ctphieuxuathang.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                            ctphieuxuathang.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                            ctphieuxuathang.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                            ctphieuxuathang.DonViTinhQuyDoi = dgvChiTiet.Rows[i].Cells[7].Value.ToString();
                            ctphieuxuathang.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                            ctphieuxuathang.SoLuongQuyDoi = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[8].Value.ToString());
                            ctphieuxuathang.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                            ctphieuxuathang.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                            ctphieuxuathang.SoKG = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[6].Value.ToString());
                            ctphieuxuathang.IsDelete = 0;

                            resultObj = ctphieuxuathangMgt.SaveNewCTPhieuXuatHang(ctphieuxuathang);
                            dgvChiTiet.Rows[i].Cells[9].Value = resultObj.ReturnCode.ToString();
                        }
                    }  
                }

                if (resultObj.ReturnCode > 0)
                {
                    //sau khi insert thanh cong
                    if (!isEdited)
                    {
                        btnDinhKhoan.Enabled = false;
                        btnInHoaDon.Enabled = false;
                        btnInPhieu.Enabled = false;

                        //***update lai vao bang hang hoa va them vao quan ly kho
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where q.SoChungTuXuat == phieuxuathang.MaSo
                                                        select q).ToList();
                         
                        {

                            List<ChiNhanhCongTy> lstChiNhanhCTy = (from cn in GetAllChiNhanhCongTy()
                                                                   where cn.Id == phieuxuathang.IdChiNhanhCongTy
                                                                   select cn).ToList();

                            
                            List<Kho> lstKho = (from k in GetAllKho()
                                                where k.TenKho == "155"
                                                select k).ToList();

                            ResultObj resObj = new ResultObj();
                            for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                            {
                                List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                            where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && 
                                                                    (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                            select htp).ToList();
                                //update bang hang hoa
                                if (lstHangHoa.Count > 0)
                                {
                                    lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                    if (lstHangHoa[0].SoLuong < 0)
                                    {
                                        lstHangHoa[0].SoLuong = 0;
                                    }
                                    resObj = hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                }
                                //insert bang Quan ly kho
                                if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                {
                                    QuanLyKho quanlykho = new QuanLyKho();
                                    quanlykho.IdKho = lstKho[0].Id;
                                    quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                    quanlykho.SoChungTuNhap = "";
                                    quanlykho.SoChungTuXuat = phieuxuathang.MaSo;

                                    resObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                }
                            }
                        }                   
                    }
                    //sau khi update thanh cong
                    else
                    {
                        btnInPhieu.Enabled = true;
                        btnInHoaDon.Enabled = true;
                        btnDinhKhoan.Enabled = true;
                        btnLuu.Enabled = false;

                        EditOrRemoveDinhKhoan(phieuxuathang.MaSo);

                        //****** update quan ly kho va hang hoa ******//
                        List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                        where q.SoChungTuXuat == phieuxuathang.MaSo
                                                        select q).ToList();

                        if (lstQuanLykho.Count > 0)
                        {
                            List<ChiNhanhCongTy> lstChiNhanhCTy = (from cn in GetAllChiNhanhCongTy()
                                                                   where cn.Id == phieuxuathang.IdChiNhanhCongTy
                                                                   select cn).ToList();

                            List<Kho> lstKho = (from k in GetAllKho()
                                                where k.TenKho == "155"
                                                select k).ToList();

                            //reset lai soluong cua bang hang hoa truoc khi cap nhat soluong hang hoa moi
                            foreach (CTPhieuXuatHang ctpx in lstmCTphieuxuathang)
                            {
                                CTPhieuXuatHang ctpxTemp = (from ct in lstDeleteCTPhieuXuatHang
                                                            where ct.Id == ctpx.Id
                                                            select ct).FirstOrDefault();
                                if(ctpxTemp == null)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == ctpx.MaHang) && (htp.Ten == ctpx.TenHang) &&
                                                                        (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + ctpx.SoLuong;
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }

                                    //update quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                             where qlk.IdHangHoa == lstHangHoa[0].Id && qlk.SoChungTuXuat == phieuxuathang.MaSo
                                                                             select qlk).ToList();

                                        if (lstQuanLyKhoReset.Count > 0)
                                        {
                                            lstQuanLyKhoReset[0].IsDelete = 1;
                                            quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                        }
                                    }
                                }
                            }

                            //bat dau cap nhat lai soluong moi vao bang Hang Hoa va quan ly kho
                            int countUpdate = this.lstmCTphieuxuathang.Count - this.lstDeleteCTPhieuXuatHang.Count;
                            int countInsert = 0;

                            if ((dgvChiTiet.Rows.Count - countUpdate) > 1)
                                countInsert = dgvChiTiet.Rows.Count - countUpdate;

                            if (countUpdate > 0)
                            {
                                for (int i = 0; i < countUpdate; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //update bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = "";
                                        quanlykho.SoChungTuXuat = phieuxuathang.MaSo;

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }

                                }
                            }

                            if (countInsert > 1)
                            {
                                for (int i = countUpdate; i < dgvChiTiet.Rows.Count - 1; i++)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == dgvChiTiet.Rows[i].Cells[1].Value.ToString()) && (htp.Ten == dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString()) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //update bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong - Convert.ToInt32(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }
                                    //insert bang Quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        QuanLyKho quanlykho = new QuanLyKho();
                                        quanlykho.IdKho = lstKho[0].Id;
                                        quanlykho.IdHangHoa = lstHangHoa[0].Id;
                                        quanlykho.SoChungTuNhap = "";
                                        quanlykho.SoChungTuXuat = phieuxuathang.MaSo;

                                        quanlykhoMgt.SaveNewQuanLyKho(quanlykho);
                                    }
                                }
                            }
                            //delete cac CTPhieuXuatHang do nguoi dung chuot phai "XOA"
                            if (this.lstDeleteCTPhieuXuatHang.Count > 0)
                            {
                                foreach (CTPhieuXuatHang ctpx in this.lstDeleteCTPhieuXuatHang)
                                {
                                    List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                                where (htp.MaSo == ctpx.MaHang) && (htp.Ten == ctpx.TenHang) && (htp.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh)
                                                                select htp).ToList();

                                    //xoa CTPhieuXuatHang
                                    ctpx.IsDelete = 1;
                                    ctphieuxuathangMgt.UpdateCTPhieuXuatHang(ctpx);

                                    //xoa bang hang hoa
                                    if (lstHangHoa.Count > 0)
                                    {
                                        lstHangHoa[0].SoLuong = lstHangHoa[0].SoLuong + ctpx.SoLuong;
                                        if (lstHangHoa[0].SoLuong < 0)
                                        {
                                            lstHangHoa[0].SoLuong = 0;
                                        }
                                        hanghoaMgt.UpdateHangHoa(lstHangHoa[0]);
                                    }

                                    //xoa quan ly kho
                                    if (lstKho.Count > 0 && lstHangHoa.Count > 0)
                                    {
                                        List<QuanLyKho> lstQuanLyKhoReset = (from qlk in GetAllQuanLyKho()
                                                                             where qlk.IdHangHoa == lstHangHoa[0].Id && qlk.SoChungTuXuat == phieuxuathang.MaSo
                                                                             select qlk).ToList();

                                        if (lstQuanLyKhoReset.Count > 0)
                                        {
                                            lstQuanLyKhoReset[0].IsDelete = 1;
                                            quanlykhoMgt.UpdateQuanLyKho(lstQuanLyKhoReset[0]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (this.lstDeleteCTPhieuXuatHang.Count > 0)
                        this.lstDeleteCTPhieuXuatHang.Clear();
                    btnLuu.Enabled = false;
                    gbThongTin.Enabled = false;
                    dgvChiTiet.Enabled = false;

                    btnThem.Enabled = true;
                    btnXoa.Enabled = true;
                    btnSua.Enabled = true;

                    MessageBox.Show("Lưu thành công !", "Thông báo");
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            prefixOld = "";
            dtOld = new DateTime();

            isEdited = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            btnDinhKhoan.Enabled = false;
            btnInHoaDon.Enabled = false;
            btnInPhieu.Enabled = false;
            gbThongTin.Enabled = true;
            dgvChiTiet.Enabled = true;
            LoadAll();            
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (this.mphieuxuathang != null)
            {
                ResultObj resultObj = new ResultObj();

                this.mphieuxuathang.IsDelete = 1;
                resultObj = phieuxuathangMgt.UpdatePhieuXuatHang(this.mphieuxuathang);
                EditOrRemoveDinhKhoan(this.mphieuxuathang.MaSo);

                List<CTPhieuXuatHang> lstCTPhieuXuatHang = (from ctpx in GetAllCTPhieuXuatHang()
                                                            where ctpx.IdPhieuXuatHang == this.mphieuxuathang.Id
                                                            select ctpx).ToList();

                if (lstCTPhieuXuatHang.Count > 0)
                {
                    foreach (CTPhieuXuatHang ctpx in lstCTPhieuXuatHang)
                    {
                        ctpx.IsDelete = 1;
                        resultObj = ctphieuxuathangMgt.UpdateCTPhieuXuatHang(ctpx);
                    }
                }

                List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                where q.SoChungTuXuat == this.mphieuxuathang.MaSo
                                                select q).ToList();

                List<ChiNhanhCongTy> lstChiNhanhCTy = (from cn in GetAllChiNhanhCongTy()
                                                where cn.Id == this.mphieuxuathang.IdChiNhanhCongTy
                                                select cn).ToList();

                if (lstQuanLykho.Count > 0 && lstChiNhanhCTy.Count > 0)
                {
                    foreach (QuanLyKho q in lstQuanLykho)
                    {
                        q.IsDelete = 1;
                        resultObj = quanlykhoMgt.UpdateQuanLyKho(q);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == q.IdHangHoa && h.NoiLuuTru == lstChiNhanhCTy[0].TenChiNhanh
                                           select h).FirstOrDefault();

                        int index = lstCTPhieuXuatHang.FindIndex(p => p.MaHang == hanghoa.MaSo);
                        hanghoa.SoLuong += lstCTPhieuXuatHang[index].SoLuong;
                        resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                    }
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Đã xoá thành công.", "Thông báo");
                    this.Close();
                    if (this.fromClosePhieuXuatHang != null)
                        fromClosePhieuXuatHang();

                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (this.mphieuxuathang != null)
            {
                isEdited = true;
                btnThem.Enabled = false;
                btnXoa.Enabled = false;
                btnLuu.Enabled = true;
                btnDinhKhoan.Enabled = false;
                btnInHoaDon.Enabled = false;
                btnInPhieu.Enabled = false;
                gbThongTin.Enabled = true;
                dgvChiTiet.Enabled = true;
            }
        }

        private void btnInPhieu_Click(object sender, EventArgs e)
        {
            string tienchu = CNum2Char.So2Chu((long)Convert.ToDouble(txtTongCong.Text));
            FrmXemReport frmView = new FrmXemReport(this.mphieuxuathang, tienchu);
            frmView.Show();
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            long tien = 0;
            tien = Convert.ToInt64(txtTongCong.Text);
            FrmDinhKhoanPhieuXuatHang frmDinhKhoanPhieuXuatHang = new FrmDinhKhoanPhieuXuatHang(tien);
            frmDinhKhoanPhieuXuatHang.formClosePhieuXuatHang += new FormClosePhieuXuatHangEventHandler(frmDinhKhoanPhieuXuatHang_formClosePhieuXuatHang);
            frmDinhKhoanPhieuXuatHang.PhieuXuatHang = this.mphieuxuathang;
            frmDinhKhoanPhieuXuatHang.TienBaoBi = Convert.ToInt64(txtTienBaoBi.Text);
            frmDinhKhoanPhieuXuatHang.Show();
        }

        private void btnInHoaDon_Click(object sender, EventArgs e)
        {
            string tienchu = CNum2Char.So2Chu((long)Convert.ToDouble(txtTongCong.Text));
            FrmXemReport frmView = new FrmXemReport(this.mphieuxuathang, tienchu, true);
            frmView.ShowDialog();

            ResultObj resultobj = new ResultObj();
            this.mphieuxuathang.NgayChungTu = DateTime.Now;
            resultobj = phieuxuathangMgt.UpdatePhieuXuatHang(mphieuxuathang);
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayThang.Value);
        }

        private void dtpNgayThang_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgayThang.Value)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, idLoaiPhieu, dtpNgayThang.Value);
        }

        public void frmDinhKhoanPhieuXuatHang_formClosePhieuXuatHang(bool IsDuyet)
        {
            btnThoat.Enabled = true;
            btnDinhKhoan.Enabled = false;
        }

        private void cboKhachHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKhachHang.SelectedItem != null)
            {
                int idKhachHang = ((KhachHang)cboKhachHang.SelectedItem).Id;
                List<KhachHang> lstKhachHang = (from kh in GetAllKhachHang()
                                                where kh.Id == idKhachHang
                                                select kh).ToList();

                if (lstKhachHang.Count > 0)
                {

                    txtMaSoThue.Text = (lstKhachHang[0].MaSoThue.ToString() == "" || lstKhachHang[0].MaSoThue.ToString() == "(NULL)" ? "" : lstKhachHang[0].MaSoThue.ToString());
                    txtChietKhau.Text = Convert.ToString(lstKhachHang[0].ChietKhau);
                    txtDiaChiGiaoHang.Text = lstKhachHang[0].DiaChi;
                    if (!string.IsNullOrEmpty(txtMaSoThue.Text))
                        txtVAT.Text = "5";
                    else
                        txtVAT.Text = "0";
                    long tongtienhang = Convert.ToInt64(txtTongTienHang.Text);
                    long ck = Convert.ToInt32(txtChietKhau.Text);
                    long chietkhau = tongtienhang * ck / 100;
                    txtTienChietKhau.Text = chietkhau.ToString();
                    long vat = (Convert.ToInt64(txtTongTienHang.Text) * Convert.ToInt64(txtVAT.Text) - chietkhau) / 100;
                    txtTienVAT.Text = vat.ToString();
                    long tongcong = (Convert.ToInt64(txtTongTienHang.Text) + Convert.ToInt64(txtVAT.Text) + Convert.ToInt64(txtTienBaoBi.Text)) - chietkhau;
                    txtTongCong.Text = tongcong.ToString();
                }

                List<ChiNhanhKhachHang> lstChiNhanhKhachHang = (from cn in GetAllChiNhanhKhachHang()
                                                                where cn.IdKhachHang == idKhachHang
                                                                select cn).ToList();

                cboChiNhanhKhachHang.DataSource = null;
                if (lstChiNhanhKhachHang.Count > 0)
                {
                    cboChiNhanhKhachHang.DataSource = lstChiNhanhKhachHang;
                    cboChiNhanhKhachHang.DisplayMember = "Ten";
                    cboChiNhanhKhachHang.ValueMember = "Id";

                    if (parentFrmChoCuocGoi != null)
                    {
                        if (parentFrmChoCuocGoi.chinhanhkhachhang.Id != 0)
                            cboChiNhanhKhachHang.SelectedItem = parentFrmChoCuocGoi.chinhanhkhachhang;
                        else
                            cboChiNhanhKhachHang.SelectedIndex = 0;
                    }
                    else if (parentFrmGoiMoiHang != null)
                    {
                        if (parentFrmGoiMoiHang.khachhang.Id != 0)
                            cboChiNhanhKhachHang.SelectedItem = parentFrmGoiMoiHang.khachhang;
                        else
                            cboChiNhanhKhachHang.SelectedIndex = 0;
                    }
                }
            }
        }

        private void cboChiNhanhKhachHang_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboChiNhanhKhachHang.SelectedIndex > -1)
            {
                int idChiNhanhKhachHang = ((ChiNhanhKhachHang)cboChiNhanhKhachHang.SelectedItem).Id;
                List<ChiNhanhKhachHang> lstChiNhanhKhachHang = (from cn in GetAllChiNhanhKhachHang()
                                                                where cn.Id == idChiNhanhKhachHang
                                                                select cn).ToList();

                if (lstChiNhanhKhachHang.Count > 0 && (lstChiNhanhKhachHang[0].MaSoThue != "" || lstChiNhanhKhachHang[0].ChietKhau.ToString() != ""))
                {
                    txtMaSoThue.Text = (lstChiNhanhKhachHang[0].MaSoThue == "" ? (txtMaSoThue.Text == "NULL"?"":txtMaSoThue.Text) : lstChiNhanhKhachHang[0].MaSoThue);
                    txtChietKhau.Text = lstChiNhanhKhachHang[0].ChietKhau.ToString();
                    txtDiaChiGiaoHang.Text = lstChiNhanhKhachHang[0].DiaChi;

                    if (!string.IsNullOrEmpty(txtMaSoThue.Text))
                        txtVAT.Text = "5";
                    else
                        txtVAT.Text = "0";

                    long tongtienhang = Convert.ToInt64(txtTongTienHang.Text);
                    long ck = Convert.ToInt32(txtChietKhau.Text);
                    long chietkhau = tongtienhang * ck / 100;
                    txtTienChietKhau.Text = chietkhau.ToString();
                    long vat = (Convert.ToInt64(txtTongTienHang.Text) * Convert.ToInt64(txtVAT.Text) - chietkhau) / 100;
                    txtTienVAT.Text = vat.ToString();
                    long tongcong = (Convert.ToInt64(txtTongTienHang.Text) + Convert.ToInt64(txtVAT.Text) + Convert.ToInt64(txtTienBaoBi.Text)) - chietkhau;
                    txtTongCong.Text = tongcong.ToString();
                }
            }
        }

        private void dgvChiTiet_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void dgvChiTiet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {           
            if (( e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6) && e.RowIndex > -1)
            {
                long num;
                if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                {
                    dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                }
                if (!Int64.TryParse(dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                {
                    MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                    dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    return;
                }
                if ( dgvChiTiet.Rows[e.RowIndex].Cells[0].Value == null)
                {
                    MessageBox.Show("Bạn chưa chọn Tên hàng ", "Thông tin");
                    return;
                }
            }

            if ((e.ColumnIndex == 3 || e.ColumnIndex == 4) && e.RowIndex != -1)
            {
                long soluong = 0;
                long dongia = 0;

                if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value != null)
                {
                    if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString() != "")
                    {
                        soluong = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString());
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                        {
                            dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (soluong * 300).ToString();                           
                        }
                        else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                        {
                            List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                                        where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                                        select htp).ToList();
                            if (lstHangHoa.Count > 0 && lstHangHoa[0].IdKhayDung > 0)
                            {
                                List<KhayDung> lstKhayDung = (from kd in GetAllKhayDung()
                                                              where kd.Id == lstHangHoa[0].IdKhayDung
                                                              select kd).ToList();
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = (lstKhayDung[0].SoLuongHop * soluong).ToString();
                            }
                            else
                                dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = 0;                           
                        }
                        else
                            dgvChiTiet.Rows[e.RowIndex].Cells[8].Value = dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString();                      
                    }
                    else
                    {
                        soluong = 0;
                        dgvChiTiet.Rows[e.RowIndex].Cells[3].Value = "0";
                    }
                }

                dongia = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[4].Value.ToString());
                long thanhtien = soluong * dongia;
                dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = thanhtien.ToString();

                long tongthanhpham = 0;
                long tongthanhtienBaoBi = 0;
                long chietkhau = 0;
                long vat = 0;
                long tongcong = 0;

                for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                {
                    string sCompare = dgvChiTiet.Rows[i].Cells[1].Value.ToString().Substring(0, 1).ToLower();
                    if (sCompare == "8" || sCompare == "9" || sCompare == "b")
                    {
                        tongthanhtienBaoBi += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                    }
                    else
                    {
                        tongthanhpham += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                    }
                }

                txtTongTienHang.Text = tongthanhpham.ToString();
                txtTienBaoBi.Text = tongthanhtienBaoBi.ToString();
                chietkhau = tongthanhpham * Convert.ToInt64(txtChietKhau.Text) / 100;
                txtTienChietKhau.Text = chietkhau.ToString();
                vat = (tongthanhpham * Convert.ToInt64(txtVAT.Text) - Convert.ToInt64(txtTienChietKhau.Text)) / 100;
                txtTienVAT.Text = vat.ToString();
                tongcong = (tongthanhpham + vat + tongthanhtienBaoBi) - chietkhau;
                txtTongCong.Text = tongcong.ToString();
            }

            if (e.ColumnIndex == 2 && e.RowIndex != -1)
            {
                if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                    dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Hộp";
                else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                    dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = "Quả";
                else
                    dgvChiTiet.Rows[e.RowIndex].Cells[7].Value = dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString();
            }
            
            if (e.ColumnIndex == 0 && e.RowIndex != -1)
            {
                dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString();
                List<HangHoa> lstHangHoa = (from htp in GetAllHangHoa()
                                            where (htp.Ten == dgvChiTiet.Rows[e.RowIndex].Cells[0].FormattedValue.ToString()) 
                                            && (htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString()) 
                                            && (((ChiNhanhCongTy)cboChiNhanhCongTy.SelectedItem).TenChiNhanh == htp.NoiLuuTru)
                                            select htp).ToList();
                if (lstHangHoa.Count > 0)
                    dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = Convert.ToInt64(lstHangHoa[0].DonGia.ToString());
                else
                    dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = 0;
            }            
        } 

        private void dgvChiTiet_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvChiTiet.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvChiTiet.ClearSelection();
                    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvChiTiet.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void FrmPhieuXuatHang_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (parentFrmChoCuocGoi != null)
                parentFrmChoCuocGoi.subThread.Abort();
            else if (parentFrmGoiMoiHang != null)
                parentFrmGoiMoiHang.subThread.Abort();
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                if (dgvChiTiet.CurrentRow.Index != (dgvChiTiet.Rows.Count - 1))
                {
                    if (dgvChiTiet.CurrentRow.Cells[9].Value != null)
                    {
                        int id = Convert.ToInt32(dgvChiTiet.CurrentRow.Cells[9].Value.ToString());
                        List<CTPhieuXuatHang> lstCTPhieuXuatHang = (from ct in GetAllCTPhieuXuatHang()
                                                                    where ct.Id == id
                                                                    select ct).ToList();
                        if (lstCTPhieuXuatHang.Count > 0)
                        {
                            if (!lstDeleteCTPhieuXuatHang.Contains(lstCTPhieuXuatHang[0]))
                                lstDeleteCTPhieuXuatHang.Add(lstCTPhieuXuatHang[0]);

                        }
                    }
                    dgvChiTiet.Rows.RemoveAt(dgvChiTiet.CurrentRow.Index);
                }
            }
        }

        private void cboKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (KhachHang b in cboKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboKhachHang.Text) && cboKhachHang.Text != "")
                {
                    cboKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhachHang.SelectedValue == null)
            {
                cboKhachHang.Text = "";
            }
        }

        private void cboChiNhanhKhachHang_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhKhachHang b in cboChiNhanhKhachHang.Items)
            {
                if (b.Ten.ToLower().Contains(cboChiNhanhKhachHang.Text) && cboChiNhanhKhachHang.Text != "")
                {
                    cboChiNhanhKhachHang.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboChiNhanhKhachHang.SelectedValue == null)
            {
                cboChiNhanhKhachHang.Text = "";
            }
        }

        private void cboChiNhanhCongTy_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboChiNhanhCongTy.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboChiNhanhCongTy.Text) && cboChiNhanhCongTy.Text != "")
                {
                    cboChiNhanhCongTy.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboChiNhanhCongTy.SelectedValue == null)
            {
                cboChiNhanhCongTy.Text = "";
            }
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        public List<DonViTinh> GetAllDonViTinh()
        {
            ResultObj resultObj = new ResultObj();
            List<DonViTinh> lstDVT = new List<DonViTinh>();

            resultObj = donvitinhMgt.GetAllDonViTinh();
            lstDVT = (List<DonViTinh>)resultObj.Result;

            return lstDVT;
        }
        
        public List<Kho> GetAllKho()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khoMgt.GetAllKho();
            List<Kho> listKho = (List<Kho>)resultObj.Result;

            return listKho;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<ChiNhanhKhachHang> GetAllChiNhanhKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhkhachangMgt.GetAllChiNhanhKhachHang();
            List<ChiNhanhKhachHang> listChiNhanhKhachHang = (List<ChiNhanhKhachHang>)resultObj.Result;

            return listChiNhanhKhachHang;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;

            return listChiNhanhCongTy;
        }

        public List<PhieuXuatHang> GetAllPhieuXuatHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = phieuxuathangMgt.GetAllPhieuXuatHang();
            List<PhieuXuatHang> listPhieuXuatHang = (List<PhieuXuatHang>)resultObj.Result;

            return listPhieuXuatHang;
        }

        public List<CTPhieuXuatHang> GetAllCTPhieuXuatHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = ctphieuxuathangMgt.GetAllCTPhieuXuatHang();
            List<CTPhieuXuatHang> listCTPhieuXuatHang = (List<CTPhieuXuatHang>)resultObj.Result;

            return listCTPhieuXuatHang;
        }

        public List<KhachHang> GetAllKhachHang()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khachhangMgt.GetAllKhachHang();
            List<KhachHang> listKhachHang = (List<KhachHang>)resultObj.Result;

            return listKhachHang;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            List<QuanLyKho> listQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return listQuanLyKho;
        }

        public List<KhayDung> GetAllKhayDung()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = khaydungMgt.GetAllKhayDung();
            List<KhayDung> listKhayDung = (List<KhayDung>)resultObj.Result;

            return listKhayDung;
        }

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listHangThanhPham = (List<HangHoa>)resultObj.Result;

            return listHangThanhPham;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }
    }
}
